import React, {useRef, useState} from 'react';
import {TouchableOpacity, TextInput} from 'react-native';
import {useNavigation} from '@react-navigation/native';
import {SafeAreaView} from 'react-native-safe-area-context';
import {Box, FlatList, Flex, Heading, HStack, Image, Input, Text, VStack} from 'native-base';
import SvgIcons from '@/assets/svg';

const Search = () => {
  const searchInputRef = useRef<TextInput>();
  const navigation = useNavigation();
  const [searchText, setSearchText] = useState('');
  const [searchHistory, setSearchHistory] = useState(['apple', 'banana', 'orange', 'pear', 'grape', 'watermelon', 'strawberry', 'peach', 'cherry']);
  const [hotSearches] = useState(['苹果', '香蕉', '橙子', '梨', '葡萄', '西瓜', '草莓', '桃子', '樱桃']);

  const handleCancelPress = () => {
    navigation.goBack();
  };

  const handleClearHistoryPress = () => {
    setSearchHistory([]);
  };

  const handleSearchPress = () => {
    // TODO: Perform search
  };

  const handleSearchTextChange = (text: string) => {
    setSearchText(text);
  };

  const handleSearchHistoryPress = (text: string) => {
    setSearchText(text);
    searchInputRef.current!.blur();
  };
  const renderSearchHistoryItem = ({item}) => {
    return (
      <Box flex={1} bg="white" borderRadius={2} m="2" py="3" alignItems="center" justifyContent="center">
        <TouchableOpacity activeOpacity={1} onPress={() => handleSearchHistoryPress(item)}>
          <Text>{item}</Text>
        </TouchableOpacity>
      </Box>
    );
  };
  const renderSearchHistory = () => {
    return (
      <Box px="6" mt="6">
        <Flex direction="row" alignItems="center" justifyContent="space-between">
          <Text bold fontSize="md">
            搜索历史
          </Text>
          <TouchableOpacity activeOpacity={1} onPress={handleClearHistoryPress}>
            <Text color="#666">清除历史</Text>
          </TouchableOpacity>
        </Flex>
        <FlatList scrollEnabled={false} data={searchHistory} numColumns={3} mt="3" renderItem={renderSearchHistoryItem}></FlatList>
      </Box>
    );
  };

  const renderHotSearches = () => {
    return (
      <Box px="6" mt="6">
        <Text bold fontSize="md">
          热门搜索
        </Text>
        <FlatList scrollEnabled={false} data={hotSearches} numColumns={3} mt="3" renderItem={renderSearchHistoryItem}></FlatList>
      </Box>
    );
  };

  const renderSearchInput = () => {
    return (
      <Box borderBottomWidth={1} px="6" borderBottomColor="#a3a3a3">
        <Flex mb="3" direction="row" alignItems="center">
          <Input h={10} mr="3" flex={1} ref={searchInputRef} variant="rounded" placeholder="Search" value={searchText} onChangeText={handleSearchTextChange} onSubmitEditing={handleSearchPress} />
          <TouchableOpacity activeOpacity={1} onPress={handleCancelPress}>
            <Text color="#007aff">取消</Text>
          </TouchableOpacity>
        </Flex>
      </Box>
    );
  };
  const renderSearchResult = () => {
    const result = new Array(10).fill({image: 'https://alifei05.cfp.cn/creative/vcg/800/new/VCG211454065967.jpg', title: '美颜数码相机，自拍不P图照样很美！', category: '数码党', viewNumber: '4.2'});
    if (searchText === 'apple') {
      return (
        <Box pl="3" mt="3" flex={1}>
          <Box alignItems="center" mt="10">
            <SvgIcons.NoSearchIcon width={200} height={200} color="#999999" />
            <Heading lineHeight="2xl" size="xl">
              没有找到匹配的结果
            </Heading>
            <Text lineHeight="2xl" color="coolGray.600">
              您可以试试下面的建议搜索
            </Text>
          </Box>
          {renderHotSearches()}
        </Box>
      );
    }
    return (
      <Box pl="3" mt="3" flex={1}>
        <FlatList
          data={result}
          renderItem={({item}) => (
            <Box pl={['0', '4']} pr="3" py="2">
              <HStack space={[2, 3]} justifyContent="space-between">
                <Image
                  width={130}
                  height={90}
                  alt="图片"
                  resizeMode="stretch"
                  source={{
                    uri: item.image,
                  }}
                />
                <VStack justifyContent="space-around">
                  <Text color="coolGray.800" bold>
                    {item.title}
                  </Text>
                  <HStack justifyContent="space-between">
                    <Text color="coolGray.600">{item.category}</Text>
                    <Text color="coolGray.600">{item.viewNumber}万人浏览</Text>
                  </HStack>
                </VStack>
              </HStack>
            </Box>
          )}
          keyExtractor={(item, index) => index.toString()}
        />
      </Box>
    );
  };
  const renderDefault = () => {
    return (
      <>
        {searchHistory.length > 0 && renderSearchHistory()}
        {hotSearches.length > 0 && renderHotSearches()}
      </>
    );
  };
  return (
    <SafeAreaView style={{flex: 1}} edges={['top', 'left', 'right', 'bottom']}>
      <Box h="full">
        {renderSearchInput()}
        {searchText ? renderSearchResult() : renderDefault()}
      </Box>
    </SafeAreaView>
  );
};

export default Search;
